import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class DatabaseUtil {
    public static final String url = "jdbc:mysql://localhost:3306/park_sys?useUnicode=true&characterEncoding=utf-8&serverTimezone=Hongkong";
    public static final String user = "root";
    public static final String password = "19950603abc";
    private static Connection conn;

    static{
        try {
            Class.forName("com.mysql.cj.jdbc.Driver").newInstance();
           conn = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConnection(){
        try{
            return DriverManager.getConnection(url, user, password);
        }catch (SQLException e){
            e.printStackTrace();
            throw new RuntimeException("Can not connect to DataBase.", e);
        }
    }

    public static boolean validateTableExist(String tableName){
        boolean flag = false;
        try {
            Connection conn = DatabaseUtil.getConnection();
            DatabaseMetaData meta = conn.getMetaData();
            String type [] = {"TABLE"};
            ResultSet rs = meta.getTables(null, null, tableName, type);
            flag = rs.next();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return flag;
    }

    public static void dropExistTable(String tableName) {
        String sql = "DROP TABLE "+tableName;
        try{
            Connection conn = DatabaseUtil.getConnection();
            Statement stmt = conn.createStatement();
            stmt.execute(sql);
            conn.close();
            stmt.close();
        } catch (Exception e){
            e.printStackTrace();
        }
    }

    public static List<String> getTableNames(){
        List<String> tableName = new ArrayList<String>();
        try{
            Connection conn = DatabaseUtil.getConnection();
            DatabaseMetaData md = conn.getMetaData();
            ResultSet rs = md.getTables(null, "park_sys", null, new String [] {"TABLE"});
            while (rs.next())
            {
                tableName.add(rs.getString(3));
            }
            conn.close();
        } catch (Exception e){
            e.printStackTrace();
        }
        return tableName;
    }
}
